import { Component } from '@angular/core';
import {AbstractControl, FormBuilder, FormGroup, Validators} from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { HttpClient } from '@angular/common/http';
import {ConstantService} from "../../services/constant.service";
import * as url from "node:url";


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  pageFunc:string = 'login';

  loginForm: FormGroup;
  showPassword:boolean = false;
  isLoading:boolean = false;

  registerForm: FormGroup;
  isRegister:boolean = false;
  showPassConfirmation:boolean = false;

  resetPasswordForm: FormGroup;
  isResetPassword:boolean = false;
  showResetPassword:boolean = false;
  showResetPasswordConfirmation:boolean = false;

  emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; //邮箱正则表达式
  userNameRegex = /^[a-zA-Z0-9_]{4,20}$/; //用户名正则表达式

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private message: NzMessageService,
    private http: HttpClient,
    private constant: ConstantService,
  ) {

    // 表单初始化：用户名/密码非空校验
    this.loginForm = this.fb.group({
      userEmail: ['', [Validators.required]],
      password: ['', [Validators.required]]
    });
    this.registerForm = this.fb.group({
      userName: [
        '',
        [
          Validators.required,
          Validators.pattern(this.userNameRegex)
        ]
      ],
      userEmail: [
        '',
        [
          Validators.required,
          Validators.pattern(this.emailRegex)
        ]
      ],
      password: ['', [Validators.required]],
      passConfirmation: [
        '',
        [
          Validators.required,
          (control: AbstractControl) => {
            const password = this.registerForm?.get('password')?.value;
            return password === control.value ? null : { passwordMismatch: true };
          }
        ]
      ]
    });
    this.resetPasswordForm = this.fb.group({
      userEmail: ['', [
        Validators.required,
        Validators.pattern(this.emailRegex)
      ]],
      password: ['', [Validators.required]],
      passwordConfirmation: ['', [
        Validators.required,
        (control: AbstractControl) => {
        const password = this.resetPasswordForm?.get('password')?.value;
        return password === control.value ? null : { passwordMismatch: true };
      }]]
    });
  }

  // 登录提交
  get loginUserEmailControl() { return this.loginForm.get('userEmail'); }
  onLogin(): void {
    if (this.loginForm.invalid) {
      // 触发表单校验
      Object.values(this.loginForm.controls).forEach(control => {
        control.markAsDirty();
        control.updateValueAndValidity();
      });
      return;
    }
    this.isLoading = true;
    const { userEmail, password } = this.loginForm.value;
    const url = this.constant.getUrl() + '/rest/login';
    this.http.post(url, { userEmail, password }).subscribe({
      next: (res:any) => {
        if(res){
          if(res.code == '0000'){
            localStorage.setItem('token',res.message);
            localStorage.setItem('userEmail', userEmail);
            localStorage.setItem('userName',res.data['userName']);
            this.router.navigate(['/']).then(() => {
              this.message.info('登陆成功!');
            });
          }else{
            this.message.warning('用户名或密码错误!');
          }
        }else{
          this.message.error('System Error!!!');
        }
      },
      error: (error) => {console.log(error.message)},
      complete: () => {
        this.isLoading = false;
      }
    });
    setTimeout(()=>{this.isLoading = false;},3000)
  }

  //注册提交
  get userNameControl() { return this.registerForm.get('userName'); }
  get userEmailControl() { return this.registerForm.get('userEmail'); }
  get passConfirmationControl() { return this.registerForm.get('passConfirmation'); }
  onRegister():void {
    if(this.registerForm.invalid) {
      Object.values(this.registerForm.controls).forEach(control => {
        control.markAsDirty();
        control.updateValueAndValidity();
      });
      return;
    }
    this.isRegister = true;
    const {userName, userEmail, password} = this.registerForm.value;
    const url = this.constant.getUrl() + '/rest/register';
    this.http.post(url, {userName, userEmail, password}).subscribe({
      next: (res:any) => {
        if(res){
          if(res.code == '0000'){
            this.message.success('注册成功，即将返回登陆界面');
            this.pageFunc = 'login';
          }else{
            this.message.warning(res.message);
          }
        }else{
          this.message.error('请求错误，请稍后重试');
        }
      }, error: (error) => {console.error(error.message)},
      complete: () => {this.isRegister = false;}
    });
    setTimeout(()=>{this.isRegister = false;},3000);
  }

  //重置密码提交
  get resetUserEmailControl() { return this.resetPasswordForm.get('userEmail'); }
  get resetPassConfirmationControl() { return this.resetPasswordForm.get('passwordConfirmation'); }
  onReset():void {
    if(this.resetPasswordForm.invalid) {
      Object.values(this.resetPasswordForm.controls).forEach(control => {
        control.markAsDirty();
        control.updateValueAndValidity();
      });
      return;
    }
    const url = this.constant.getUrl() + '/rest/resetPass';
    const {userEmail, password} = this.resetPasswordForm.value;
    this.isResetPassword = true;
    this.http.post(url, {userEmail, password}).subscribe({
      next: (res:any) => {
        if(res){
          if(res.code == '0000'){
            this.message.success('修改成功，返回登陆界面');
            this.pageFunc = 'login';
          }else{
            this.message.warning(res.message);
          }
        }
      }, error: (error) => {console.error('error: ', error.message)},
      complete: () => {this.isResetPassword = false;}
    });
    setTimeout(()=>{this.isResetPassword = false;},3000);
  }
  //切换按钮
  onRegisterSwitchClick():void {this.pageFunc = 'register';this.loginForm.reset();}
  onLoginSwitchClick():void {this.pageFunc = 'login';this.registerForm.reset();}
  onForgotPasswordClick():void {this.pageFunc = 'resetPassword';this.resetPasswordForm.reset();}
}
